<template>
  <div class="app-container">
    <el-button v-waves type="primary" @click="handleAdd">创建账户</el-button>

    <el-table
      :data="table.data"
      row-key = "accountId"
      v-loading="table.listLoading"
      style="width: 100%;margin-top:30px;"
      border
    >
      <el-table-column align="center" label="用户账号">
        <template slot-scope="scope">
          {{ scope.row.accountName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户编号">
        <template slot-scope="scope">
          {{ scope.row.accountCode }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="用户名称">
        <template slot-scope="scope">
          {{ scope.row.systemUsername }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="隶属部门">
        <template slot-scope="scope">
          {{ scope.row.priorityPrincipal.department.departmentName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="主要职务">
        <template slot-scope="scope">
          {{ scope.row.priorityPrincipal.duty.dutyName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-tag :type="formatStatusTag(scope.row)">{{formatStatus(scope.row)}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" width="180px">
        <template slot-scope="scope">
          <el-button v-waves type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
          <el-button v-waves type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="table.total > 0" :total="table.total" :page.sync="table.listQuery.page" :pageSizes.sync="table.pageSizes"  :limit.sync="table.listQuery.limit" @pagination="getTableList" />
    <el-dialog :visible.sync="dialog.visible" :title="dialog.title">
      <el-form :model="account" label-width="120px" label-position="left" style="margin: 0px 20px 0px 20px">
        <el-form-item label="用户账号">
          <el-input v-model="account.accountName" placeholder="账户名称" />
        </el-form-item>
        <el-form-item label="用户名称">
          <el-input v-model="account.systemUsername" placeholder="职位代码" />
        </el-form-item>
        <el-form-item label="用户编号">
          <el-input v-model="account.accountCode" placeholder="账号编码" />
        </el-form-item>
        <el-form-item label="隶属部门">
          <el-select v-model="account.departmentId" placeholder="请选择">
            <el-option
              v-for="item in dictDept"
              :key="item.departmentId"
              :label="item.departmentName+ ' ( '+item.departmentCode+' ) '"
              :value="item.departmentId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门职务">
          <el-select v-model="account.dutyId" placeholder="请选择" ref="dutySelect">
            <el-option
              v-for="item in deptDuties"
              :key="item.dutyId"
              :label="item.dutyName"
              :value="item.dutyId">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialog.visible=false">取消</el-button>
        <el-button type="primary" @click="confirmSave">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination'
import { deepClone } from '@/utils'
import { loadDepartment } from '@/api/dict'
import { searchAccount, addAccount } from '@/api/account'

const defaultAccount = {
  accountId: null,
  accountName: null,
  accountCode: null,
  systemUsername: null,
  departmentId: null,
  dutyId: null,
  securityStatus: null
}

export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      dictDept: [],
      account: deepClone(defaultAccount),
      table: {
        total: 0,
        data: [],
        listLoading: true,
        pageSizes: [10, 20, 30, 50, 100],
        listQuery: {
          page: 1,
          limit: 10,
          sort: ''
        }
      },
      dialog: {
        visible: false,
        title: '创建账号'
      }
    }
  },
  computed: {
    deptDuties() {
      this.$nextTick(() => {
        this.account.dutyId = null
      })
      const departmentId = this.account.departmentId
      if (!departmentId) {
        return []
      }
      const dept = this.dictDept.find(v => v.departmentId === departmentId)
      if (!dept) {
        return []
      }
      return dept.duties
    }
  },
  created() {
    try {
      Promise.all([this.getTableList(), this.loadDictDepartment()])
    } catch (e) {
      console.log(e)
    }
  },
  methods: {
    async loadDictDepartment() {
      this.dictDept = await loadDepartment()
    },
    async getTableList() {
      this.table.listLoading = true
      const res = await searchAccount(this.table.listQuery)
      this.table.data = res.result
      this.table.total = parseInt(res.total)
      this.table.listLoading = false
    },
    async confirmSave() {
      await addAccount(this.account)
      const { accountName, systemUsername, accountCode } = this.account
      const notify = { // notify
        title: '创建成功',
        type: 'success',
        dangerouslyUseHTMLString: true,
        message: `<div>账户名: ${accountName}</div><div>用户名: ${systemUsername}</div><div>账户编码: ${accountCode}</div>`
      }
      this.$notify(notify)
      this.dialog.visible = false// close dialog
      this.getTableList() // reload table
    },
    handleAdd() { // 执行添加职位
      this.dialog.visible = true // open dialog
    },
    handleEdit(scope) { // 执行修改职位
      const id = scope.row.accountId
      this.$router.push({ path: `/account/edit/${id}` })
    },
    handleDelete({ $index, row }) { // 执行删除职位
      this.$confirm('确认删除该职务 ?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          // await disableDuty(row.dutyId)
          this.table.data.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功'
          })
        })
        .catch(err => { console.error(err) })
    },
    formatStatusTag(account) {
      if (account.securityStatus === 0) {
        return 'success'
      } else {
        return 'danger'
      }
    },
    formatStatus(account) {
      if (account.securityStatus === 0) {
        return '正常'
      }

      if (account.securityStatus === 1) {
        return '被锁定'
      }

      if (account.securityStatus === 4) {
        return '禁用'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
